#!/usr/bin/env node

var fs = require('fs');
var d3 = require('d3-queue');
var path = require('path');

var q = d3.queue(1);

fs.readdirSync('./packages').forEach(function(dir) {
  q.defer(scopePackage, dir);
});

function scopeName(name) {
  if (name.match(/^turf/)) {
    return '@' + name.replace(/-/, '/');
  } else {
    return name;
  }
}

function objMap(obj, map) {
  var newObj = {};
  for (var k in obj) {
    var res = map([k, obj[k]]);
    newObj[res[0]] = res[1];
  }
  return newObj;
}

function prefixDependency(kv) {
  return [scopeName(kv[0]), kv[1]];
}

function scopePackage(directory, callback) {
  var pkgPath = path.join('./packages/', directory, '/package.json');
  var pkg = JSON.parse(fs.readFileSync(pkgPath));
  pkg.name = scopeName(pkg.name);
  pkg.dependencies = objMap(pkg.dependencies || {}, prefixDependency);
  pkg.devDependencies = objMap(pkg.devDependencies || {}, prefixDependency);
  fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
  callback();
}
